﻿using UnityEngine;
using System.Collections;

public class HealthPickup : MonoBehaviour
{
    public float healthBonus;               // 箱子为玩家提供的生命值加成
    public AudioClip collect;               // 拾取箱子时的音效

    private PickupSpawner pickupSpawner;    // 引用拾取物生成器
    private Animator anim;                  // 引用动画组件
    private bool landed;                

    void Awake()
    {
        // 设置引用
        pickupSpawner = GameObject.Find("pickupManager").GetComponent<PickupSpawner>();
        anim = transform.root.GetComponent<Animator>();
    }

    void OnTriggerEnter2D(Collider2D other)
    {
        // 如果玩家进入触发区域...
        if (other.tag == "Player")
        {
            // 获取玩家生命值脚本的引用
            PlayerHealth playerHealth = other.GetComponent<PlayerHealth>();

            // 增加玩家生命值（按加成值），但不超过100
            playerHealth.health += healthBonus;
            playerHealth.health = Mathf.Clamp(playerHealth.health, 0f, 100f);

            // 更新生命值条
            playerHealth.UpdateHealthBar();

            // 触发新的拾取物生成，启动协程
            pickupSpawner.StartCoroutine(pickupSpawner.DeliverPickup());

            // 播放拾取音效
            AudioSource.PlayClipAtPoint(collect, transform.position);

            // 销毁箱子
            Destroy(transform.root.gameObject);
        }
        // 如果箱子撞到地面且尚未着陆...
        else if (other.tag == "ground" && !landed)
        {
            // ...触发Land动画参数
            anim.SetTrigger("Land");

            transform.parent = null;//将当前游戏对象从父物体中分离，
            gameObject.AddComponent<Rigidbody2D>();//动态添加一个 Rigidbody2D 组件
            landed = true;
        }
    }
}